import Taro from "@tarojs/taro"
import { getUser, setLoginUser, applyToken } from "./index"
import Http from "./http"

let refreshTokenStatus
export default async function RefreshToken() {
  const currentTime = new Date().getTime()
  const loginTime = Number(Taro.getStorageSync("login_time"))
  const tokenData = getUser()
  if (loginTime && tokenData) {
    const { expiresIn, refreshToken } = tokenData
    const splitTime = expiresIn - (currentTime - loginTime) / 1000
    // console.log("splitTime>>>>>>>>>>", splitTime)
    if (splitTime < 600) {
      // token过期时间小于10分钟获取新token
      const params = {
        refreshToken: refreshToken,
      }
      // 确保同一时间段内只执行一次
      if (!refreshTokenStatus) {
        try {
          refreshTokenStatus = true
          const { data, code }: any = await Http.post("/diet/login/refreshToken", params)
          refreshTokenStatus = undefined
          if (code != 0) return "err"
          const time = String(new Date().getTime())
          Taro.setStorageSync("login_time", time)
          applyToken(data?.accessToken)
          setLoginUser({ ...data })
          return "success"
        } catch (error) {
          refreshTokenStatus = undefined
          return "err"
        }
      } else {
        // 正在获取token，不再重复请求
        return "pending"
      }
    } else {
      // 未到过期时间，不请求
      refreshTokenStatus = undefined
      return ""
    }
  }
}
